package com.yinhai.common.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.yinhai.common.dao.DaoSupport;
/**
 * 
 * @Description: 用户验证service
 * @Date: 2016年1月20日 下午3:31:04
 * @author: yuan
 */
@Service("userAuthService")
public class MyUserDetailsService implements UserDetailsService {
	
	public static Logger logger =  Logger.getLogger(MyUserDetailsService.class);
	
	@Autowired
	private DaoSupport baseDao;
	
	@SuppressWarnings("rawtypes")
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserDetails user = null;
		try {
			Map dbUser =  (Map) baseDao.findForObject("auth.findByUserName", username);
			user = new User(dbUser.get("name").toString(), dbUser.get("password").toString(), true, true, true, true, getAuthorities());
		} catch (Exception e) {
			logger.error("用户名未找到！");
			throw new UsernameNotFoundException("用户名未找到！");
		}
		return user;
	}
	/**
	 * 
	 * @Description: 获得用户角色
	 * @return
	 */
	public Collection<? extends GrantedAuthority> getAuthorities() {
		//ROLE_USER角色
		List<SimpleGrantedAuthority> authos = new ArrayList<>();
		SimpleGrantedAuthority sim = new SimpleGrantedAuthority("ROLE_USER");
		authos.add(sim);
		return authos;
	}

}
